package com.imay.live.fragment.user;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.live.BuildConfig;
import com.imay.live.R;
import com.imay.live.activity.BasePermissionActivity;
import com.imay.live.activity.MainActivity2;
import com.imay.live.activity.WebViewActivity;
import com.imay.live.activity.user.LoginActivity;
import com.imay.live.activity.user.ResigterActivity;
import com.imay.live.activity.user.UserActivity;
import com.imay.live.activity.user.util.AppCheck;
import com.imay.live.activity.user.util.UMDeleteAuthListener;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.fragment.load.LoadMokeyFragment;
import com.imay.live.helper.CallBack;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.H5Helper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.helper.UrlHelper;
import com.imay.live.manager.AccountManager;
import com.imay.live.model.ServerDomainModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.AppUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.tbas_api.IMYScheduler;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/8 0008.
 */

public class UserFragment extends UserBaseFragment implements View.OnClickListener {
    private int mPosition = -1;
    private Context mContext, ap;
    private LinearLayout mWBlogin, mQQLogin, mWXLogin;
    private String loadServerListCommand;
    private String fromurl;

    private final int REQUESTPERMISSION = 1;

    private static UserFragment instance;

    public static UserFragment getInstance() {
        return new UserFragment();
    }

    @Override
    public void setArguments(Bundle args) {
        super.setArguments(args);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_user;
    }

    @Override
    protected boolean useDynamicTitleBar() {
        return false;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mPosition = -1;
        mContext = getActivity();
        ap = getActivity().getApplicationContext();

//        List<String> permissions = new ArrayList<String>();
//
//        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//            permissions.add(Manifest.permission.READ_PHONE_STATE);
//        }
//
//        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//            permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
//        }
//
//        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//            permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
//        }
//
//        if (!permissions.isEmpty()) {
//            String[] permissionArr = new String[permissions.size()];
//            permissions.toArray(permissionArr);
//            ActivityCompat.requestPermissions(getActivity(), permissionArr, REQUESTPERMISSION);
//        } else {
//            appAcivation();
//        }


        //((TextView)$(R.id.tv_register)).setText(SpannableStringUtils.getBuilder(getString(R.string.str_login_phone_register)).setUnderline().create());
        //$(R.id.tv_register).setOnClickListener(this);
        $(R.id.tv_login_phone).setOnClickListener(this);
        $(R.id.tv_clause).setOnClickListener(this);
        $(R.id.view_bg_user).setOnClickListener(this);


        // 登录
        mWBlogin = $(R.id.ll_login_weibo);
        mWBlogin.setOnClickListener(this);
        $(R.id.tv_login_weibo).setOnClickListener(this);
        $(R.id.ll_login_phone).setOnClickListener(this);

        if (!AppCheck.isQQClientAvailable(ap)) {
            ImageView imageView = $(R.id.tv_login_qq);
            imageView.setImageResource(R.mipmap.com_qq_3);
        } else {
            $(R.id.tv_login_qq).setOnClickListener(this);
            mQQLogin = $(R.id.ll_login_qq);
            mQQLogin.setOnClickListener(this);
        }

        if (!AppCheck.isWeixinAvilible(ap)) {
            ImageView imageView = $(R.id.tv_login_weixin);
            imageView.setImageResource(R.mipmap.com_weixin_3);
        } else {
            $(R.id.tv_login_weixin).setOnClickListener(this);
            mWXLogin = $(R.id.ll_login_weixin);
            mWXLogin.setOnClickListener(this);
        }
        MobclickAgent.onEvent(mContext, "login_open");
        PreferenceHelper.getInstance().putLong(PreferenceHelper.ROOMHOUSE_TIME, 0);//建楼卡
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onClick(View view) {
        final ArrayList<SnsPlatform> platforms = AccountManager.getInstance().getPlatforms();
        switch (view.getId()) {
            /*case R.id.tv_register:
                toResigter();
                MobclickAgent.onEvent(mContext, "login_click_register");
                break;*/
            case R.id.ll_login_phone:
            case R.id.tv_login_phone:
                toLogin();
                //LoginActivity.startActivity(getActivity(), fromurl);
                MobclickAgent.onEvent(mContext, "login_click_shouji");
                break;
            case R.id.tv_clause:

                WebViewActivity.startActivity(getActivity(), getString(R.string.str_user_clause_title), UrlHelper.URL);
                break;
            case R.id.tv_login_weibo:
            case R.id.ll_login_weibo:
                DialogFragmentHelper.showLoadingDialog(getChildFragmentManager(), getString(R.string.str_loading));
                mWBlogin.setClickable(false);
                if (UMShareAPI.get(mContext).isAuthorize(getActivity(), platforms.get(1).mPlatform)) {
                    UMShareAPI.get(mContext).deleteOauth(getActivity(), platforms.get(1).mPlatform, new UMDeleteAuthListener() {
                        @Override
                        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                            UMShareAPI.get(getActivity()).doOauthVerify(getActivity(), platforms.get(1).mPlatform, umAuthListener);
                        }
                    });
                } else {
                    UMShareAPI.get(getActivity()).doOauthVerify(getActivity(), platforms.get(1).mPlatform, umAuthListener);
                }
                mPosition = 1;
                MobclickAgent.onEvent(mContext, "login_click_weibo");
                break;
            case R.id.tv_login_weixin:
            case R.id.ll_login_weixin:
                DialogFragmentHelper.showLoadingDialog(getChildFragmentManager(), getString(R.string.str_loading));
                mWXLogin.setClickable(false);
                if (UMShareAPI.get(mContext).isAuthorize(getActivity(), platforms.get(2).mPlatform)) {
                    UMShareAPI.get(mContext).deleteOauth(getActivity(), platforms.get(2).mPlatform, new UMDeleteAuthListener() {
                        @Override
                        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                            UMShareAPI.get(getActivity()).doOauthVerify(getActivity(), platforms.get(2).mPlatform, umAuthListener);
                        }
                    });
                } else {
                    UMShareAPI.get(mContext).doOauthVerify(getActivity(), platforms.get(2).mPlatform, umAuthListener);
                }
                mPosition = 2;
                MobclickAgent.onEvent(mContext, "login_click_weixin");
                break;
            case R.id.tv_login_qq:
            case R.id.ll_login_qq:
                DialogFragmentHelper.showLoadingDialog(getChildFragmentManager(), getString(R.string.str_loading));
                mQQLogin.setClickable(false);
                if (UMShareAPI.get(mContext).isAuthorize(getActivity(), platforms.get(0).mPlatform)) {
                    UMShareAPI.get(mContext).deleteOauth(getActivity(), platforms.get(0).mPlatform, new UMDeleteAuthListener() {
                        @Override
                        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                            UMShareAPI.get(getActivity()).doOauthVerify(getActivity(), platforms.get(0).mPlatform, umAuthListener);
                        }
                    });
                } else {
                    UMShareAPI.get(getActivity()).doOauthVerify(getActivity(), platforms.get(0).mPlatform, umAuthListener);
                }
                mPosition = 0;
                MobclickAgent.onEvent(mContext, "login_click_qq");
                break;
            case R.id.view_bg_user:
                if (!BuildConfig.IS_RELEASE) {
                    loadServerList();
                }
                break;
        }
    }

    // 友盟回调
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            //授权开始的回调
            if (mQQLogin != null) {
                mQQLogin.setClickable(true);
            }
            if (mWBlogin != null) {
                mWBlogin.setClickable(true);
            }
            if (mWXLogin != null) {
                mWXLogin.setClickable(true);
            }
            if (platform == SHARE_MEDIA.SINA) {
                DialogFragmentHelper.closeLoadingDialog(getChildFragmentManager());
            }
        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            if (data == null) {
                return;
            }
            //DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), getString(R.string.str_login_loading));
            final JSONObject json = new JSONObject(data);
            final AccountManager accountManager = AccountManager.getInstance();
            if (platform == SHARE_MEDIA.QQ) {
                accountManager.loginByQQ(json.toString(), callBack);
            } else if (platform == SHARE_MEDIA.WEIXIN) {
                accountManager.loginByWechat(json.toString(), callBack);
            } else if (platform == SHARE_MEDIA.SINA) {
                accountManager.loginByWB(json.toString(), callBack);
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            DialogFragmentHelper.closeLoadingDialog(getChildFragmentManager());
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            DialogFragmentHelper.closeLoadingDialog(getChildFragmentManager());
        }
    };

    // 返回信息
    private CallBack callBack = new CallBack() {
        @Override
        public void onSuccess() {
            ToastUtil.showImg(mContext, getString(R.string.str_login_success), R.mipmap.jiaohutishidagou_3x, 200);
            DialogFragmentHelper.closeLoadingDialog(getChildFragmentManager());
            if (getActivity() instanceof MainUserListener) {
                ((MainUserListener) getActivity()).startMain();
            }
        }

        @Override
        public void onError(int code, String message) {
            DialogFragmentHelper.closeLoadingDialog(getChildFragmentManager());
            ToastUtil.showImg(mContext, ErrorResult.getString(mContext, code), R.mipmap.jiaohutishidaxia_3x, 200);
        }
    };

    private void loadServerList() {
        DialogFragmentHelper.showLoadingDialog(getChildFragmentManager(), "");
        loadServerListCommand = ProtoRequestHelper.task(ProtoHttpFactory.getServerList()).setTag(this.hashCode()).request(this);
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        DialogFragmentHelper.closeLoadingDialog(getChildFragmentManager());
        super.onRequestSuccess(command, data);
        if (command.equals(loadServerListCommand)) {
            try {
                Result<List<ServerDomainModel>> result = JSON.parseObject(data, new TypeReference<Result<List<ServerDomainModel>>>() {
                }.getType());
                showServerListDialog(result.data);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        super.onRequestError(command, code, message);
        DialogFragmentHelper.closeLoadingDialog(getChildFragmentManager());
    }

    /**
     * 服务器选择
     *
     * @param serverDomainModels
     */
    private void showServerListDialog(final List<ServerDomainModel> serverDomainModels) {
        if (serverDomainModels == null || serverDomainModels.isEmpty()) {
            return;
        }
        List<CharSequence> itemList = new ArrayList<>(serverDomainModels.size());
        for (ServerDomainModel model : serverDomainModels) {
            itemList.add(model.getName() + ": " + model.getIp());
        }
        final CharSequence[] charSequences = new CharSequence[itemList.size()];
        itemList.toArray(charSequences);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setItems(charSequences, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String url = serverDomainModels.get(which).getIp();

                IMYScheduler.getInstance().setSocketAddress(url, 7000);
                IMYScheduler.getInstance().stopSocketService();
                IMYScheduler.getInstance().startSocketService();

                UrlHelper.setTestSocketDomain(url);
                if (url.contains("192.168")) {
                    UrlHelper.setTestApiDomain("http://" + url + ":7999");
                } else {
                    UrlHelper.setTestApiDomain("http://" + url);
                }

            }
        }).show();
    }

}
